# 使用提醒:
# 1. xbot包提供软件自动化、数据表格、Excel、日志、AI等功能
# 2. package包提供访问当前应用数据的功能，如获取元素、访问全局变量、获取资源文件等功能
# 3. 当此模块作为流程独立运行时执行main函数
# 4. 可视化流程中可以通过"调用模块"的指令使用此模块

# import xbot
# from xbot import print, sleep
# from . import package
import json
import sys


def main(args):
    pass
from collections import Counter
import uiautomator2 as u2
import time
import re
import os, subprocess, random
import threading
import pyperclip
from wechat.vedio.tools import upload_data, upload_img, get_token, get_search_data, error_log

# adb_path = "C:\\Users\\Admin\\Desktop\\platform-tools\\"
# adb_path = "C:\\Users\\有赞\\Desktop\\platform-tools\\"
adb_path = "C:\\android-sdk-windows\\platform-tools\\"


def excute_cmd(cmd):
    return subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, universal_newlines=True, encoding='UTF-8').stdout

def intoWechat(d):
    print("intoWechat")
    condition = d.app_current()

    if condition["package"] != 'com.tencent.mm':
        d.app_start("com.tencent.mm")
        if not d(text="发现").exists:
            d.app_stop("com.tencent.mm")
            d.uiautomator.stop()
            d.uiautomator.start()
            d.app_start("com.tencent.mm")
    else:
        d.app_stop("com.tencent.mm")
        d.uiautomator.stop()
        d.uiautomator.start()
        d.app_start("com.tencent.mm")

    time.sleep(1)
    d(text="发现").click()
    time.sleep(1)
    d(text="直播和附近").click()
    time.sleep(2)
    if d.xpath('//*[@resource-id="com.tencent.mm:id/e1x"]').exists:
        d.xpath('//*[@resource-id="com.tencent.mm:id/e1x"]').click()
    if d.xpath(
        "//*[@resource-id='com.tencent.mm:id/kfj']/android.widget.FrameLayout/android.widget.RelativeLayout").exists:
        d.xpath(
            "//*[@resource-id='com.tencent.mm:id/kfj']/android.widget.FrameLayout/android.widget.RelativeLayout").click()
    time.sleep(1)

def restartWechat(d):
    print("intoWechat")
    d.app_stop("com.tencent.mm")
    d.uiautomator.stop()
    d.uiautomator.start()
    d.app_start("com.tencent.mm")
    time.sleep(1)
    d(text="发现").click()
    time.sleep(1)
    d(text="直播和附近").click()
    time.sleep(1)
    if d.xpath('//*[@resource-id="com.tencent.mm:id/e1x"]').exists:
        d.xpath('//*[@resource-id="com.tencent.mm:id/e1x"]').click()
    d.xpath(
        "//*[@resource-id='com.tencent.mm:id/kfj']/android.widget.FrameLayout/android.widget.RelativeLayout").click()
    time.sleep(1)

def getNums(d):
    print("getNums")
    str = ""
    time.sleep(5)
    if d.xpath('//*[@resource-id="com.tencent.mm:id/ftj"]').exists:
        str = d.xpath('//*[@resource-id="com.tencent.mm:id/ftj"]').get_text()
    list = str.split("人看过")
    listRes =[]
    if list[0].find("万") != -1:
        listRes.insert(0, int(eval(list[0][:-1]) * 10000))
    else:
        listRes.insert(0, int(list[0]))
    if list[1] != "":
        if list[1].find("万") != -1:
            i = list[1].index("万")
            listRes.insert(1, int(eval(list[1][3:i]) * 10000))
        else:
            j = list[1].index("热")
            listRes.insert(1, int(list[1][3:j]))

    return listRes

def checkShopBag(device):
    print("checkShopBag")
    shopBagExist = False
    if device.xpath('com.tencent.mm:id/cxc').exists:
        shopBagExist = True
    return shopBagExist

def getThemeBase(d):
    print("getThemeBase")
    value1 = ""
    value2 = ""
    value3 = ""
    themeBase = {}
    if d.xpath('//*[@resource-id="com.tencent.mm:id/cpr"]/android.widget.FrameLayout[2]/android.widget.RelativeLayout/android.widget.TextView').exists:
        value1 = d.xpath('//*[@resource-id="com.tencent.mm:id/cpr"]/android.widget.FrameLayout[2]/android.widget.RelativeLayout/android.widget.TextView').get_text()

    if d.xpath('//*[@resource-id="com.tencent.mm:id/cpr"]/android.widget.FrameLayout[3]/android.widget.RelativeLayout/android.widget.TextView').exists:
        value2 = d.xpath('//*[@resource-id="com.tencent.mm:id/cpr"]/android.widget.FrameLayout[3]/android.widget.RelativeLayout/android.widget.TextView').get_text()

    if d.xpath(
            '//*[@resource-id="com.tencent.mm:id/cpr"]/android.widget.FrameLayout[4]/android.widget.RelativeLayout/android.widget.TextView').exists:
        value3 = d.xpath(
            '//*[@resource-id="com.tencent.mm:id/cpr"]/android.widget.FrameLayout[4]/android.widget.RelativeLayout/android.widget.TextView').get_text()

    if value1.startswith("主题") or value1.startswith("位置"):
        themeBase[value1[:2]] = value1[3:-1]
    if value2.startswith("主题") or value2.startswith("位置"):
        themeBase[value2[:2]] = value2[3:-1]
    if value1.startswith("公众号"):
        themeBase[value1[:3]] = value1[4:-1]
    elif value2.startswith("公众号"):
        themeBase[value2[:3]] = value2[4:-1]
    elif value3.startswith("公众号"):
        themeBase[value3[:3]] = value3[4:-1]
    return themeBase

def getName(d):
    return d.xpath(
            '//*[@resource-id="com.tencent.mm:id/emj"]').get_text()

def getZan(d):
    print("getZan")
    zanNum = 0
    zan = "0"
    if d.xpath('//*[@resource-id="com.tencent.mm:id/cs8"]').exists:
        zan = d.xpath('//*[@resource-id="com.tencent.mm:id/cs8"]').get_text()
    if zan.find("万") != -1:
        zanNum = int(eval(zan[:-1]) * 10000)
    else:
        zanNum = int(zan)
    return zanNum


def getComment(d):
    print("getComment")
    comments = {}
    tempList = []

    for i in range(1,10,1):
        if d.xpath('//*[@resource-id="com.tencent.mm:id/ege"]').exists:
            d.xpath('//*[@resource-id="com.tencent.mm:id/ege"]').click()
        if d.xpath('//*[@resource-id="com.tencent.mm:id/cpr"]/android.widget.FrameLayout[%d]/android.widget.RelativeLayout/android.widget.TextView' % i).exists:
            value1 = d.xpath('//*[@resource-id="com.tencent.mm:id/cpr"]/android.widget.FrameLayout[%d]/android.widget.RelativeLayout/android.widget.TextView'% i).get_text()
            if value1.find("：") != -1:
                tempList = value1.split("：")
            else:
                continue
            if value1.startswith("主题") or value1.startswith("位置") or  value1.startswith("通知") or  value1.startswith("礼物") or value1.startswith("公众号"):
                continue
            elif Counter(comments.values())[tempList[1]] > 2:
                continue
            else:
                comments[tempList[0]] = tempList[1]
        else:
            break
    return comments

def getIncreaseComs(d,comments,currentTime,minutes):
    size = len(comments)
    i = 0
    tempList = []

    while int(time.time()) < currentTime + minutes * 60:
        if d.xpath('d(resourceId="com.tencent.mm:id/ege"').exists:
            d.xpath('d(resourceId="com.tencent.mm:id/ege"').click()
        i = i+1
        if d.xpath('//*[@resource-id="com.tencent.mm:id/cpr"]/android.widget.FrameLayout[%d]/android.widget.RelativeLayout/android.widget.TextView' % i).exists:
            value1 = d.xpath('//*[@resource-id="com.tencent.mm:id/cpr"]/android.widget.FrameLayout[%d]/android.widget.RelativeLayout/android.widget.TextView' % i).get_text()
            if value1.find("：") != -1:
                tempList = value1.split("：")
            else:
                continue
            if value1.startswith("主题") or value1.startswith("位置") or value1.startswith("通知") or value1.startswith("礼物") or value1.startswith("公众号"):
                continue
            else:
                if (tempList[0] in comments.keys()) and (tempList[1] == comments.get(tempList[0])):
                    continue
                elif Counter(comments.values())[tempList[1]] > 2:
                    continue
                else:
                    comments[tempList[0]] = tempList[1]
        else:
            i = i - 1
    return len(comments) - size


def checkCertific(d):
    if d.xpath('//*[@resource-id="com.tencent.mm:id/emk"]').exists:
        return True
    else:
        return False

def checkBase(d):
    if not d.xpath('//*[@resource-id="com.tencent.mm:id/emh"]').exists:
        restartWechat(d)

def getGoodsBagDetails(d, shopBagExist):
    print("getGoodsBagDetails")
    goodsBag = {}
    if shopBagExist:
        d.xpath('com.tencent.mm:id/cxc').click()
        time.sleep(3)
        for i in range(1,10,1):
            if d.xpath('//*[@resource-id="com.tencent.mm:id/cxh"]/android.widget.FrameLayout[%d]/android.widget.RelativeLayout/android.widget.RelativeLayout/android.widget.LinearLayout/android.widget.LinearLayout/android.widget.TextView' % i).exists:
                value =d.xpath('//*[@resource-id="com.tencent.mm:id/cxh"]/android.widget.FrameLayout[%d]/android.widget.RelativeLayout/android.widget.RelativeLayout/android.widget.LinearLayout/android.widget.LinearLayout/android.widget.TextView' % i).get_text()
                if value not in goodsBag.keys():
                    goodsBag[value] = 1
                else:
                    goodsBag[value] = goodsBag.get(value) + 1
            else:
                # - | - |
                d.swipe(0.5, 0.8, 0.5, 0.637, 0.2)
        d.press("back")
    return goodsBag

def checkSelfSell(d,getGoodsBagDetails):
    print("checkSelfSell")
    extrnalList = ["爱逛","有赞","魔筷","拼多多","京东","唯品会","当当","猫眼","饷店","微盟","贝省"]
    externalSellFlag = False
    for k in getGoodsBagDetails.keys():
        if k in extrnalList:
            externalSellFlag = True
        else:
            continue
    return externalSellFlag

def toMainPage(d):
    d.xpath('//*[@resource-id="com.tencent.mm:id/emh"]').click()

def getMainDetails(d):
    print("start getMainDetails")
    mainDetails = {}
    certifcType = "blue"
    certificTypeName = ""
    mainIntroduct = ""
    toMainPage(d)
    time.sleep(2)
    # 是否存在展开字段
    if d.xpath('//*[@resource-id="com.tencent.mm:id/d25"]/android.widget.TextView[1]').exists:
        d.xpath('//*[@resource-id="com.tencent.mm:id/d25"]/android.widget.TextView[1]').click()
    # 是否存在认证信息
    if d.xpath('//*[@resource-id="com.tencent.mm:id/d1m"]').exists:
        certificTypeName = d.xpath('//*[@resource-id="com.tencent.mm:id/d1m"]').get_text()
        if certificTypeName.find("主播") != -1 or certificTypeName.find("博主") != -1 or certificTypeName.find("自媒体") != -1:
            certifcType = "whiteYellow"
        mainDetails["certifcType"] = certifcType
        mainDetails["certificTypeName"] = certificTypeName
    else:
        mainDetails["certifcType"] = certifcType
    # 获取简介
    if d.xpath('//*[@resource-id="com.tencent.mm:id/d25"]/android.widget.TextView').exists:
        mainIntroduct = d.xpath('//*[@resource-id="com.tencent.mm:id/d25"]/android.widget.TextView').get_text()
    # 存在只有2行，是视图
    elif d.xpath('//*[@resource-id="com.tencent.mm:id/ctk"]').exists:
        d.long_click(111,530)
        if d(text="复制").exists:
            d(text="复制").click()
        os1 = r"%sadb.exe shell am startservice ca.zgrs.clipper/.ClipboardService" % adb_path
        os2 = r"%sadb.exe -s %s shell am broadcast -a clipper.get" % (adb_path, d.serial)
        os.system(os1)
        d.app_start("ca.zgrs.clipper")
        time.sleep(1)
        mainIntroduct = excute_cmd(os2)
        mainIntroduct = mainIntroduct.split("data=")[1][1:-2]
        d.press("back")
    mainDetails["mainIntroduct"] = mainIntroduct
    # 是否存在公众号
    if d.xpath('//*[@resource-id="com.tencent.mm:id/fbi"]').exists:
        publicWechatName = d.xpath('//*[@resource-id="com.tencent.mm:id/fbi"]').get_text()
        if publicWechatName.startswith("公众号"):
            publicWechatName = certificTypeName.split(":")[1][1:]
            if publicWechatName != "":
                mainDetails["publicWechatName"] = publicWechatName
    if d.xpath('//*[@content-desc="商品"]').exists:
        mainDetails["goodsWindow"] = True
    else:
        mainDetails["goodsWindow"] = False
    d.press("back")
    if  d.xpath('//*[@resource-id="com.tencent.mm:id/fbi"]').exists:
        d.press("back")
    return mainDetails

def runStart(device):
    resultMap = {}
    result = []
    try:
        d = u2.connect(device)
        intoWechat(d)
        # 直播间停留时间
        waitTime = 1

        while 1:
            try:
                if not checkCertific(d):
                    time.sleep(2)
                    d.swipe(0.5, 0.4, 0.5, 0.1, 0.2)
                    time.sleep(2)
                    checkBase(d)
                    continue
                else:
                    # 主播名称
                    name = getName(d)
                    # 认证状态
                    certific = checkCertific(d)
                    # 获取主题和位置
                    themeBase = getThemeBase(d)
                    # 获取场观 和 热度
                    beforeWatchedNum = getNums(d)
                    # 获赞数
                    beforeZanNum = getZan(d)
                    # 获取当前评论
                    comments = getComment(d)
                    # 获取当前时间戳
                    currentTime = int(time.time())
                    # 停留时间增加的评论数和每分钟的平均评论数
                    increaseCom = getIncreaseComs(d,comments,currentTime,waitTime)
                    avgIncreaseComments = increaseCom/waitTime
                    # 停留时间每分钟增加的场观  or 场观过万增加1k需要的时间
                    avgOneMinInsWatchedNum = 0
                    increasedTimeEveryThousand = 0
                    oneMinInsWatchedNum = getNums(d)
                    if oneMinInsWatchedNum[0] < 10000:
                        avgOneMinInsWatchedNum = (oneMinInsWatchedNum[0] - beforeWatchedNum[0])/waitTime
                    else:
                        avgOneMinInsWatchedNum = "场观超过1w，不想等"
                        # 场观过万增加1k需要的时间
                    # else:
                    #     while oneMinInsWatchedNum[0] < beforeWatchedNum[0] + 1000:
                    #         oneMinInsWatchedNum = getNums(d)
                    #     increasedTimeEveryThousand = int(time.time()) - currentTime
                    # 停留时间增加的点赞
                    increasedZan = getZan(d) - beforeZanNum
                    # 是否有购物袋
                    shopBagExist = checkShopBag(d)
                    # 以字典方式获取10个商品的店铺与数量
                    goodsBagDe = getGoodsBagDetails(d, shopBagExist)
                    # 判断是否有带第三方，Ture=有第三方
                    externalSellFlag = checkSelfSell(d, goodsBagDe)
                    # 获取主页消息
                    mainDetails = getMainDetails(d)
                    d.swipe(0.5, 0.4, 0.5, 0.1, 0.2)
                    time.sleep(2)
                    # 检测UI位置
                    checkBase(d)
                    resultMap["主播名称"] = name
                    resultMap["是否认证"] = certific
                    resultMap["主题位置公众号"] = themeBase
                    resultMap["停留时间(分钟)"] = str(waitTime)
                    resultMap["停留时间增加的评论"] = increaseCom
                    resultMap["每分钟平均增加的评论"] = avgIncreaseComments
                    resultMap["场观数"] = oneMinInsWatchedNum
                    resultMap["每分钟平均增加的观看量"] = avgOneMinInsWatchedNum
                    resultMap["点赞数"] = beforeZanNum
                    resultMap["增加的点赞数"] = increasedZan
                    resultMap["是否带货"] = shopBagExist
                    resultMap["货源平台"] = goodsBagDe
                    resultMap["主播主页信息"] = mainDetails

                    resultJson = json.dumps(resultMap,ensure_ascii=False)
                    result.append(resultJson)
                    print(time.strftime('%Y-%m-%d %H:%M:%S ',time.localtime(time.time())))
                    print(result)

            except Exception as e:
                print(device, e)
                # error_log(other=e)
                intoWechat(d)
                # continue
    except Exception as e:
        print("主流程异常", e)
        error_log(other=e)
        # runStart(device)


def get_devices():
    '''获取已经链接的手机id'''
    # devices_info = os.popen("C:\\Users\\有赞\\Desktop\\platform-tools\\adb.exe devices -l").read()
    devices_info = os.popen('''%sadb.exe devices -l''' % adb_path).read()
    splited_devices = devices_info.split('\n')[1:]


    result_list = []
    for device in splited_devices:
        if device:
            id = re.findall("(\w+) +device product", device)[0]
            result_list.append(id)

    print(result_list)
    return result_list


def thread_run():
    devices = get_devices()
    thread = []
    os.system('''%sadb.exe kill-server ''' % adb_path)
    os.system('''%sadb.exe start-server ''' % adb_path)
    time.sleep(3)
    for i in devices:
        thread.append(threading.Thread(target=runStart, args=(i,)))  # 创建一个线程
        # t.start()  # 启动线程
    for t in thread:
        t.start()

    for t in thread:
        t.join()

if __name__ == '__main__':
    thread_run()